package util;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;


import java.io.File;
import java.util.concurrent.TimeUnit;


public class WebDriverFactory {

    public static final String CHROME = "chrome";
    public static final String FIREFOX = "firefox";

    public WebDriver initDriver (String browser)
    {
        WebDriver testDriver = setDefaultConfiguration(browser);
        return testDriver;
    }

    private WebDriver setDefaultConfiguration(String browser)
    {
        WebDriver driver = null;
        DesiredCapabilities capabilities = setDefaultCapabilities(browser);

        if (browser.equals(FIREFOX))
        {
            driver = new FirefoxDriver(capabilities);
        } else
        if (browser.equals(CHROME))
        {
            File file = new File(PropertyLoader.loadProperty("selenium.chrome.driver.path"));
            System.setProperty("webdriver.chrome.driver",file.getAbsolutePath());
            driver = new ChromeDriver(capabilities);
        } else

        driver.manage().timeouts().implicitlyWait(Integer.parseInt(PropertyLoader.loadProperty("selenium.implicitly.wait")), TimeUnit.SECONDS);

        return driver;
    }

    private DesiredCapabilities setDefaultCapabilities(String browser)
    {
        DesiredCapabilities capabilities = new DesiredCapabilities();

        if (browser.contains(FIREFOX)){
            capabilities = DesiredCapabilities.firefox();
        } else
        if (browser.contains(CHROME)){
            capabilities = DesiredCapabilities.chrome();
        }else
            Assert.fail(ReportWriter.errorDriverUnknown(browser));

        return capabilities;
    }
}


